<template>
  <div class="PC">
    <el-form :inline="true" :model="formInline" class="demo-form-inline">
      <el-form-item label="姓名">
        <el-input v-model="formInline.username" placeholder="请输入姓名" clearable />
      </el-form-item>

      <el-form-item label="手机号">
        <el-input v-model="formInline.phone" placeholder="请输入手机号" clearable />
      </el-form-item>

      <el-form-item label="职位">
        <el-select v-model="formInline.department" placeholder="请选择职位" clearable>
          <el-option label="HR" value="HR" />
          <el-option label="员工" value="员工" />
          <el-option label="行政" value="行政" />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button style="background-color: #253963; color: #fff" @click="onSubmit"
          >查询</el-button
        >
        <el-button @click="handleReset">重置</el-button>
      </el-form-item>
    </el-form>
    <div style="margin-bottom: 16px">
      <el-button type="primary" @click="showAddDialog">添加</el-button>
    </div>
    <el-table
      :data="tableData"
      style="width: 100%; margin-top: 20px; font-size: 15px"
      :stripe="true"
      border
      header-cell-class-name="custom-header"
      row-class-name="custom-row"
    >
      <el-table-column prop="username" label="姓名" />
      <el-table-column prop="id" label="工号" />
      <el-table-column prop="department" label="职位" />
      <el-table-column prop="phone" label="手机号" />
      <el-table-column prop="id" label="操作">
        <template #default="scope">
          <el-button class="op-btn edit-btn" link size="small" @click="cha(scope.row)"
            >编辑</el-button
          >
          <el-button
            class="op-btn delete-btn"
            link
            size="small"
            @click="handleDelete(scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
  </div>

  <div class="move" style="padding-top: 20px">
    <el-form :inline="true" :model="formInline" style="width: 90vw; margin: 0 auto">
      <el-form-item label="姓名">
        <el-input v-model="formInline.username" placeholder="请输入姓名" clearable />
      </el-form-item>

      <el-form-item label="手机号">
        <el-input v-model="formInline.phone" placeholder="请输入手机号" clearable />
      </el-form-item>

      <el-form-item label="职位">
        <el-select v-model="formInline.department" placeholder="请选择职位" clearable>
          <el-option label="HR" value="HR" />
          <el-option label="员工" value="员工" />
          <el-option label="行政" value="行政" />
        </el-select>
      </el-form-item>
      <br />
      <el-form-item>
        <el-button style="background-color: #253963; color: #fff" @click="onSubmit"
          >查询</el-button
        >
        <el-button @click="handleReset">重置</el-button>
      </el-form-item>
    </el-form>

    <el-card
      style="max-width: 90vw; margin: 0 auto; margin-top: 10px; font-size: 14px"
      v-for="item in tableData"
    >
      <p>
        姓名：<span style="color: #bbb9b7">{{ item.username }}</span>
      </p>
      <p>
        工号：<span style="color: #bbb9b7">{{ item.id }}</span>
      </p>
      <p>
        职位：<span style="color: #bbb9b7">{{ item.department }}</span>
      </p>
      <p>
        手机号：<span style="color: #bbb9b7">{{ item.phone }}</span>
      </p>
      <template #footer>
        <el-button :link="true" size="small" style="color: #203a64" @click="cha(item)"
          >编辑</el-button
        >
        <el-button
          size="small"
          style="background-color: red; color: #fff"
          @click="del(item)"
          >删除</el-button
        >
      </template>
    </el-card>
  </div>

  <el-dialog
    title="编辑用户"
    v-model="editDialogVisible"
    :width="isMobile ? '95vw' : '500px'"
    :style="isMobile ? 'min-width: unset; max-width: 100vw;' : ''"
    @close="handleCancel"
  >
    <el-form :model="form" :rules="rules" ref="editFormRef" label-width="100px">
      <el-form-item label="姓名" prop="username">
        <el-input v-model="form.username" placeholder="请输入" />
      </el-form-item>
      <el-form-item label="手机号" prop="phone">
        <el-input v-model="form.phone" placeholder="请输入手机号" />
      </el-form-item>
      <el-form-item label="职位" prop="department">
        <el-select v-model="form.department" placeholder="请选择职位">
          <el-option label="HR" value="HR" />
          <el-option label="员工" value="员工" />
          <el-option label="行政" value="行政" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <div class="dialog-footer-right">
          <el-button @click="handleCancel">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确认</el-button>
        </div>
      </el-form-item>
    </el-form>
  </el-dialog>

  <el-dialog
    title="添加用户"
    v-model="addDialogVisible"
    :width="isMobile ? '95vw' : '500px'"
    :style="isMobile ? 'min-width: unset; max-width: 100vw;' : ''"
    @close="handleAddCancel"
  >
    <el-form :model="addForm" :rules="rules" ref="addFormRef" label-width="100px">
      <el-form-item label="姓名" prop="username">
        <el-input v-model="addForm.username" placeholder="请输入" />
      </el-form-item>
      <el-form-item label="手机号" prop="phone">
        <el-input v-model="addForm.phone" placeholder="请输入手机号" />
      </el-form-item>
      <el-form-item label="职位" prop="department">
        <el-select v-model="addForm.department" placeholder="请选择职位">
          <el-option label="HR" value="HR" />
          <el-option label="员工" value="员工" />
          <el-option label="行政" value="行政" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <div class="dialog-footer-right">
          <el-button @click="handleAddCancel">取消</el-button>
          <el-button type="primary" @click="handleAddSubmit">确认</el-button>
        </div>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script setup lang="ts">
import { reactive, ref, onMounted, watch, onUnmounted } from "vue";
import {
  getAllUsers,
  queryUserByMultiConditions,
  deleteUser,
  updateuser,
  addTable,
} from "../utils/api.ts";
import { ElMessageBox, ElMessage } from "element-plus";
import type { FormRules, FormInstance } from "element-plus";
// import { emit } from "process";

interface UserType {
  id: string;
  username: string;
  phone: string;
  department: string;
}

const dialogVisible = ref(false);
const tableData = ref<UserType[]>([]);
const data = ref<UserType | null>(null);

const total = ref(0);
const pageSize = ref(5);
const currentPage = ref(1);

const getData = async () => {
  const res = await getAllUsers();
  tableData.value = Array.isArray(res.data) ? res.data : [];
  console.log("表格数据：", tableData.value);
};

onMounted(() => {
  getData();
});

interface formInlineTS {
  username: string;
  phone: string;
  department: string;
  status: string;
}

const formInline: formInlineTS = reactive({
  username: "",
  phone: "",
  department: "",
  status: "",
});

const onSubmit = async () => {
  const res = await queryUserByMultiConditions(formInline);
  tableData.value = Array.isArray(res.data) ? res.data : [];
};
const colseAdd = (val: boolean) => {
  dialogVisible.value = val;
};
const editDialogVisible = ref(false);
const editFormRef = ref<FormInstance>();
const form = reactive<Partial<UserType>>({
  username: "",
  phone: "",
  department: "",
});
const rules = reactive<FormRules>({
  username: [{ required: true, message: "请输入姓名", trigger: "blur" }],
  phone: [
    { required: true, message: "请输入手机号", trigger: "blur" },
    { pattern: /^1[3-9]\d{9}$/, message: "请输入正确的手机号", trigger: "blur" },
  ],
  department: [{ required: true, message: "请选择职位", trigger: "change" }],
});

const cha = (row: UserType) => {
  Object.assign(form, row);
  editDialogVisible.value = true;
};

const handleSubmit = async () => {
  editFormRef.value?.validate(async (valid) => {
    if (valid) {
      try {
        console.log("编辑用户ID:", form.id, form);
        await updateuser(form.id, form);
        await getData();
        ElMessage.success("编辑成功");
        editDialogVisible.value = false;
        editFormRef.value?.resetFields();
      } catch (error) {
        ElMessage.error("编辑失败，请重试");
        console.error("编辑请求失败:", error);
      }
    }
  });
};

const handleCancel = () => {
  editDialogVisible.value = false;
  editFormRef.value?.resetFields();
};

const del = async (value: any) => {
  await deleteUser(value.id);
  getData();
};

const handleDelete = async (row: UserType) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除「${row.username || row.department || ""}」吗？`,
      "删除确认",
      {
        type: "warning",
        confirmButtonText: "确认",
        cancelButtonText: "取消",
      }
    );
    await deleteUser(row.id);
    getData();
    ElMessage.success("删除成功");
  } catch (error) {
    if (error === "cancel") {
      ElMessage.info("已取消删除");
    } else {
      ElMessage.error("删除失败，请重试");
    }
  }
};

const handleSizeChange = (val: any) => {
  pageSize.value = val;
  // getData();
};
const handleCurrentChange = (val: any) => {
  currentPage.value = val;
  // getData();
};

const isMobile = ref(window.innerWidth < 1000);
const handleResize = () => {
  isMobile.value = window.innerWidth < 1000;
};
onMounted(() => window.addEventListener("resize", handleResize));
onUnmounted(() => window.removeEventListener("resize", handleResize));

const handleReset = () => {
  formInline.username = "";
  formInline.phone = "";
  formInline.department = "";
  formInline.status = "";
  getData();
};

const addDialogVisible = ref(false);
const addFormRef = ref<FormInstance>();
const addForm = reactive({
  employeestype: "",
  id: "",
  username: "",
  phone: "",
  department: "",
  password: "",
});
function showAddDialog() {
  addDialogVisible.value = true;
  addForm.employeestype = "";
  addForm.id = "";
  addForm.username = "";
  addForm.phone = "";
  addForm.department = "";
  addForm.password = "";
}
function handleAddCancel() {
  addDialogVisible.value = false;
  addFormRef.value?.resetFields();
}
async function handleAddSubmit() {
  addFormRef.value?.validate(async (valid) => {
    if (valid) {
      try {
        console.log("添加用户数据：", addForm);
        await addTable(addForm);
        await getData();
        ElMessage.success("添加成功");
        addDialogVisible.value = false;
        addFormRef.value?.resetFields();
      } catch (error) {
        ElMessage.error("添加失败，请重试");
        console.error("添加请求失败:", error);
      }
    }
  });
}
</script>

<style scoped>
@media (max-width: 1000px) {
  .PC {
    display: none;
  }
  .move {
    display: block;
  }
}
@media (min-width: 1000px) {
  .PC {
    display: block;
  }
  .move {
    display: none;
  }
}

.demo-form-inline {
  margin-top: 30px;
}

.custom-header {
  font-weight: bold;
  background: #f8f9fb;
}
.el-table {
  font-size: 15px;
  background: #fff;
  border-radius: 0;
  box-shadow: none;
}
.el-table th.custom-header {
  font-weight: bold;
  background: #f8f9fb;
  color: #222;
  font-size: 15px;
  border-bottom: 1px solid #ebeef5;
  height: 44px;
}
.el-table td {
  font-size: 15px;
  color: #222;
  border-bottom: 1px solid #ebeef5;
  height: 44px;
  padding: 0 8px;
}
.el-table .cell {
  padding: 0 8px;
  line-height: 44px;
}
.el-table__body tr.custom-row:hover > td {
  background: #f5f7fa;
}
.el-table__body tr.custom-row > td {
  background: #fff;
}
.el-table th,
.el-table td {
  border-bottom: 1px solid #ebeef5;
}
.el-table__header,
.el-table__body {
  border-radius: 0;
}
.el-pagination {
  margin-top: 16px;
}

.op-btn {
  padding: 0 6px;
  font-size: 15px;
  font-weight: 400;
  border: none;
  box-shadow: none;
  background: none;
  min-width: unset;
  height: unset;
  line-height: 1.5;
  margin: 0 2px;
}
.edit-btn {
  color: #203a64;
  transition: color 0.2s;
}
.edit-btn:hover {
  color: #162447;
  background: none;
}
.delete-btn {
  color: #203a64;
  transition: color 0.2s;
}
.delete-btn:hover {
  color: #162447;
  background: none;
}

.delete-center-dialog .el-dialog__body {
  padding-top: 10px;
  padding-bottom: 10px;
}
.delete-center-dialog .el-dialog__header {
  text-align: left;
  padding-bottom: 0;
}
</style>
